import { doLoginApi } from '@/api/loginApi'
import { setToken } from '@/utils/token'
import sessionStore from '@/utils/sessionStore'

export default {
  state: {
    token: '',
    uname: '',
    uid: 0,
    role: '',
    menu: []
  },
  /* getters: {
    token: state => state.token || getToken()
  }, */
  mutations: {
    addToken(state, token) {
      setToken(token)
      state.token = token
    },
    setUname(state, uname) {
      state.uname = uname
    },
    setUid(state, uid) {
      state.uid = uid
    },
    addRole(state, role) {
      sessionStore.set('role', role)
      state.role = role
    },
    addMenu(state, menu) {
      sessionStore.set('menu', menu)
      state.menu = menu
    },
  },
  actions: {
    // 一定要有返回值
    async loginAction({ commit }, userData) {
      let ret = await doLoginApi(userData)
      if (ret.code === 0) {
        commit('addToken', ret.data.token)
        commit('setUname', ret.data.name)
        commit('setUid', ret.data.uid)
        commit('addRole', ret.data.role)
        commit('addMenu', ret.data.menu)
      }
      return ret.code === 0 ? true : false
    }
  }
}